﻿//1、命名空间
var MiniCore = {};
MiniCore.Box = function () {
    this.Data = {};
}
//2、定义替换$key$为数据的模板
String.prototype.ReplaceTemplate = function (key, recnt) {
    var content = this;
    var tkey = "content.replace(/\\{\\$" + key + "\\$\\}/g,'" + recnt + "')";
    var tkey2 = "content.replace(/\\%7B\\$" + key + "\\$\\%7D/g,'" + recnt + "')";
    try {
        content = eval(tkey);
    } catch (e) {
        tkey = "content.replace(/\\{\\$" + key + "\\$\\}/g,'')";
        content = eval(tkey);
    }
    try {
        content = eval(tkey2);
    } catch (e) {
        tkey2 = "content.replace(/\\%7B\\$" + key + "\\$\\%7D/g,'')";
        content = eval(tkey2);
    }
    return content;
}
//3、运用模板将$key$全替换成数据（本例中<tr>标签中含有$key$替换成json数据）
String.prototype.ReplaceJson = function (json) {
    if (json == null) { return this };
    var tmp = this;
    for (n in json) {
        if (json[n] == null) {

            tmp = tmp.ReplaceTemplate(n, "");
        }
        else {
            tmp = tmp.ReplaceTemplate(n, json[n]);
        }
    }
    return tmp;
}
//4、定义移除模板的函数
function Clear(templateID) {
    var parent = $("#" + templateID).prev();
    var tid = "ID" + new Date().getTime();
    parent.attr("ID", tid);
    $("#" + tid + ">[id!='" + templateID + "']").remove();
    return parent;
}
//5、循环绑定追加Json数据
MiniCore.Box.prototype.Bind = function (templateID) {
    var instance = Clear(templateID);
    var templateHtml = $("#" + templateID).html();
    for (var i = 0; i < this.Data.length; i++) {
        instance.append(templateHtml.ReplaceJson(this.Data[i]));
    }
    return this;
}